package com.jinglin.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.jinglin.entity.enums.DateTimePatternEnum;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.swing.text.StyledEditorKit;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Component
public class OssUtils {
    private String endpoint = "https://oss-cn-shenzhen.aliyuncs.com";
    private String accessKeyId = "LTAI5tHj6wfkmzKuQvWjS2em";
    private String accessKeySecret = "pWxXTkAhpAPzzc6pa8oQ5tGzNxMxi4";
    public String uploadImage(MultipartFile file, String bucketName){
        String month = DateUtil.format(new Date(), DateTimePatternEnum.YYYYMM.getPattern());

        int i = file.getOriginalFilename().lastIndexOf(".");
        String substring = file.getOriginalFilename().substring(i);
        // OSS文件路径
        String ossFilePath = month + "/"+ UUID.randomUUID() + substring;


        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ossClient.putObject(bucketName,ossFilePath,file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
        return ossFilePath;

    }
    public OSSObject getObject(String bucketName,String OssPath){
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        return ossClient.getObject(bucketName,OssPath);
    }

    public String uploadFile(MultipartFile chunkFile, String filePath, String bucketName) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ossClient.putObject(bucketName,filePath,chunkFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
        return filePath;

    }
}
